package org.client;

import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.common.CommonConfig;
import org.common.dispatcher.ProtoDispatcher;
import org.common.netty.NettyClient;
import org.common.BaseMain;
import org.common.netty.Pack;
import org.common.netty.PackCodec;
import org.common.utils.ClassScannerUtils;
import org.common.utils.RandomUtils;
import org.common.utils.SpringUtils;
import org.protobuf.AccountMsg;
import org.protobuf.ProtoEnumMsg;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashSet;
import java.util.Set;


/**
 * 测试用客户端
 */
@Component
@Slf4j
public class ClientMain extends BaseMain {

    Channel channel;

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ClientBeanConfig.class);
        context.start();

        ClientMain clientMain = SpringUtils.getBean(ClientMain.class);
        clientMain.init();

        System.exit(0);
    }


    @Override
    protected void handleBackGroundCmd(String cmd) {
        if (cmd.equals("test")) {
            channel.writeAndFlush("test".getBytes());
        } else if (cmd.startsWith("register_")) {
            String[] s = cmd.split("_");
            if (s.length != 3) {
                return;
            }
            String accountName = s[1];
            String password = s[2];
            AccountMsg.C2SAccountRegister.Builder builder = AccountMsg.C2SAccountRegister.newBuilder();
            builder.setAccountName(accountName);
            builder.setPassword(password);
            Pack pack = new Pack(ProtoEnumMsg.CMD.ID.ACCOUNT_REGISTER_VALUE, builder.build().toByteArray());
            byte[] data = PackCodec.encode(pack);
            channel.writeAndFlush(data);
        } else if (cmd.startsWith("login_")) {
            String[] s = cmd.split("_");
            if (s.length != 3) {
                return;
            }
            String accountName = s[1];
            String password = s[2];
            AccountMsg.C2SAccountLogin.Builder builder = AccountMsg.C2SAccountLogin.newBuilder();
            builder.setAccountName(accountName);
            builder.setPassword(password);
            Pack pack = new Pack(ProtoEnumMsg.CMD.ID.ACCOUNT_LOGIN_VALUE, builder.build().toByteArray());
            byte[] data = PackCodec.encode(pack);
            channel.writeAndFlush(data);
        } else if (cmd.startsWith("createRole_")) {
            // 创建角色
            String[] s = cmd.split("_");
            if (s.length != 2) {
                return;
            }
            String nick = s[1];
            AccountMsg.C2SRoleCreate.Builder builder = AccountMsg.C2SRoleCreate.newBuilder();
            builder.setName(nick);
            Pack pack = new Pack(ProtoEnumMsg.CMD.ID.ROLE_CREATE_VALUE, builder.build().toByteArray());
            byte[] data = PackCodec.encode(pack);
            channel.writeAndFlush(data);
        } else if (cmd.startsWith("loginRole_")) {
            String[] s = cmd.split("_");
            if (s.length != 2) {
                return;
            }
            long roleId = Long.parseLong(s[1]);
            AccountMsg.C2SRoleLogin.Builder builder = AccountMsg.C2SRoleLogin.newBuilder();
            builder.setRoleId(roleId);
            Pack pack = new Pack(ProtoEnumMsg.CMD.ID.ROLE_LOGIN_VALUE, builder.build().toByteArray());
            byte[] data = PackCodec.encode(pack);
            channel.writeAndFlush(data);
        }
    }

    @Override
    protected void initServer() {
        CommonConfig commonConfig = SpringUtils.getBean(CommonConfig.class);
        //netty启动
        NettyClient nettyClient = SpringUtils.getBean(NettyClient.class);
        String loginPlayerHost = commonConfig.getLoginPlayerHost();
        String[] hostArray = loginPlayerHost.split(",");
        Set<String[]> hostSet = new HashSet<>();
        for (String host : hostArray) {
            String[] ipAndPort = host.split(":");
            if (ipAndPort.length != 2) {
                log.error("login host error!{}", loginPlayerHost);
                continue;
            }
            hostSet.add(ipAndPort);
        }
        // 随机一个login进行登录
        String[] ipAndPort = RandomUtils.selectOne(hostSet);
        String ip = ipAndPort[0];
        String port = ipAndPort[1];
        channel = nettyClient.start(ip, Integer.parseInt(port), new ClientNettyHandler());

        // 协议转发器初始化
        Set<Class<?>> classes;
        try {
            classes = ClassScannerUtils.getClasses("org.client");
            ProtoDispatcher protoDispatcher = SpringUtils.getBean(ProtoDispatcher.class);
            protoDispatcher.load(classes);
        } catch (IOException | ClassNotFoundException | NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }
}

